package com.bbcloud.service.impl;

import com.bbcloud.common.Const;
import com.bbcloud.common.ResponseCode;
import com.bbcloud.common.ServerResponse;
import com.bbcloud.common.TokenCache;
import com.bbcloud.dao.ActivityMapper;
import com.bbcloud.dao.DayMapper;
import com.bbcloud.dao.DeviceMapper;
import com.bbcloud.dao.UserMapper;
import com.bbcloud.pojo.Activity;
import com.bbcloud.pojo.Day;
import com.bbcloud.pojo.Device;
import com.bbcloud.pojo.User;
import com.bbcloud.service.IDayService;
import com.bbcloud.service.IFileService;
import com.bbcloud.util.IDUtil;
import com.bbcloud.util.PropertiesUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * Created by liuzhu on 2018/11/23.
 */

@Service("iDayService")
public class DayServiceImpl implements IDayService{

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private DayMapper dayMapper;
    @Autowired
    private IFileService iFileService;
    @Autowired
    private DeviceMapper deviceMapper;

    @Override
    public ServerResponse<PageInfo>getActivityByDayId(String token,String userId, String dayId,int pageNum,int pageSize,String orderBy){
        User user = userMapper.selectUser(userId);
        if (user == null){
            return ServerResponse.createByErrorMessage("The user doesn't exist.");
        }
        String tokenValid = TokenCache.getKey(TokenCache.TOKEN_PREFIX+user.getEmail());
        if (!StringUtils.equals(tokenValid,token)){
            return ServerResponse.createByErrorMessage("Please log in again");
        }
        PageHelper.startPage(pageNum,pageSize);
        List<Activity> activityList = activityMapper.selectByUserIdAndDayId(StringUtils.isBlank(userId)?" ":userId,StringUtils.isBlank(dayId)?" ":dayId);
        PageInfo pageResult = new PageInfo(activityList);
        pageResult.setList(activityList);
        return ServerResponse.createBySuccess(pageResult);
    }

    public ServerResponse saveActivity(String token,String userId,String dayId,String activityLines,String deviceId,int distance,int usedTime,int speedAvg){
        User user = userMapper.selectUser(userId);
        if (user == null){
            return ServerResponse.createByErrorMessage("The user doesn't exist.");
        }
        String tokenValid = TokenCache.getKey(TokenCache.TOKEN_PREFIX+user.getEmail());
        if (!StringUtils.equals(tokenValid,token)){
            return ServerResponse.createByErrorMessage("Please log in again");
        }
        Activity activity = new Activity();
        activity.setActivityId(IDUtil.ActivityID());
        activity.setUserId(userId);
        activity.setDayId(dayId);
        activity.setActivityType(Const.ActivityType.TYPE_DRIVE);
        activity.setStatus(Const.ActivityStatus.STATUS_FINISH);
        activity.setDeviceId(deviceId);
        activity.setActivityLines(activityLines);
        activity.setDistance(distance);
        activity.setUsedTime(usedTime);
        activity.setSpeedAvg(speedAvg);
        int rowCount = activityMapper.insert(activity);
        int rowCountDay = 0;
        if (rowCount == 0){
            return ServerResponse.createByErrorMessage("save activity record failed!");
        }
        Day day = dayMapper.selectByDayIdAndUserId(userId,dayId);
        if (day == null){
            day = new Day();
            day.setUserId(userId);
            day.setDayId(dayId);
            day.setIsclocked(Const.DayIsClock.ISCLOCK_FALSE);
            day.setTimes(1);
            day.setTotalDistance(distance);
            day.setTotalTime(usedTime);
            rowCountDay = dayMapper.insert(day);
        }
        else {
            int times = day.getTimes();
            int totalDistance = day.getTotalDistance();
            int totalTime = day.getTotalTime();
            day.setTimes(times+1);
            day.setTotalDistance(totalDistance+distance);
            day.setTotalTime(totalTime+usedTime);
            rowCountDay = dayMapper.updateByPrimaryKeySelective(day);
        }
        if (rowCountDay == 0){
            activityMapper.deleteByActivityId(activity.getActivityId());
            return ServerResponse.createByErrorMessage("save activity record failed!");
        }
        Device device = deviceMapper.selectByinvitationCode(deviceId);
        Integer totalDistance = device.getMileage();
        totalDistance += distance;
        device.setMileage(totalDistance);
        deviceMapper.updateByPrimaryKeySelective(device);
        return ServerResponse.createBySuccess();
    }

    public  ServerResponse<Day> clock(String token,String userId,String dayId,String description,String path,MultipartFile file){
        User user = userMapper.selectUser(userId);
        if (user == null){
            return ServerResponse.createByErrorMessage("The user doesn't exist.");
        }
        String tokenValid = TokenCache.getKey(TokenCache.TOKEN_PREFIX+user.getEmail());
        if (!StringUtils.equals(tokenValid,token)){
            return ServerResponse.createByErrorMessage("Please log in again");
        }
        String targetFileName = iFileService.upload(file,path);
        String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;
        Map fileMap = Maps.newHashMap();
        fileMap.put("uri",targetFileName);
        fileMap.put("url",url);
        Day day = dayMapper.selectByDayIdAndUserId(userId,dayId);
        if (day == null) {
            return ServerResponse.createByErrorMessage("clock failed");
        }
//        Day day = new Day();
//        day.setDayId(dayId);
        day.setClockDes(description);
        day.setClockImage(url);
//        List<Activity> activityList = activityMapper.selectByUserIdAndDayId(StringUtils.isBlank(userId)?" ":userId,StringUtils.isBlank(dayId)?" ":dayId);
//        day.setTimes(activityList.size());
//        for (Activity activity:activityList){
//            day.setTotalDistance(day.getTotalDistance()+activity.getDistance());
//            day.setTotalTime(day.getTotalTime()+activity.getUsedTime());
//        }
        day.setIsclocked(Const.DayIsClock.ISCLOCK_TRUE);
        int rowCount = dayMapper.updateByPrimaryKeySelective(day);
        if (rowCount == 0){
            return ServerResponse.createByErrorMessage("clock failed!");
        }
        return ServerResponse.createBySuccess(day);
    }

    public ServerResponse<Day> selectDayWithDayIdAndUserId(String token,String userId,String dayId){
        User user = userMapper.selectUser(userId);
        if (user == null){
            return ServerResponse.createByErrorMessage("The user doesn't exist.");
        }
        String tokenValid = TokenCache.getKey(TokenCache.TOKEN_PREFIX+user.getEmail());
        if (!StringUtils.equals(tokenValid,token)){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"Please login again");
        }
        Day day = dayMapper.selectByDayIdAndUserId(userId,dayId);
        if (day == null) {
            return ServerResponse.createByErrorMessage("get the day info failed");
        }
        return ServerResponse.createBySuccess(day);
    }
}
